import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/util/ExamUtil.dart';
import 'package:ichinesereader/exam/widgets/BGSinglePlayer.dart';
import 'package:ichinesereader/exam/widgets/SampleAudioPlayer.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsGradesResult.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:intl/intl.dart';
import 'TeacherIBSpeakingController.dart';

class TeacherIBSpeakingPage extends GetView<TeacherIBSpeakingController> {
  TeacherIBSpeakingPage(
      {required this.assessmentId,
      required this.questionRecordId,
      required this.studentName,
      required this.status,
      Key? key})
      : super(key: key);
  static const String routeName = '/reports/IBSpeaking';
  final String assessmentId;
  final String questionRecordId;
  final String studentName;
  final String status;
  final Color blackTextColor = Get.isDarkMode ? Colors.white54 : Colors.black;
  final Color whiteTextColor = Get.isDarkMode ? Colors.black54 : Colors.white;
  @override
  Widget build(BuildContext context) {
    MediaQuery.of(context).size.width;
    if (StrUtil.hasValue(assessmentId) && controller.stepTop.value == -1) {
      controller.isCompleted = (status == 'COMPLETED');
      controller.getAssessmentByStudentName(
          assessmentId, studentName, questionRecordId);
    }
    return Scaffold(
        body: Padding(
            padding: EdgeInsets.only(top: 25),
            child: Stack(children: [
              Obx(() {
                return _buildRunningRecordPage(
                    context, controller.stepTop.value);
              }),
              Positioned(
                  right: 20,
                  child: FloatingActionButton(
                      onPressed: () {
                        Get.back();
                      },
                      backgroundColor: Theme.of(context).colorScheme.secondary,
                      child: const Icon(Icons.close_rounded),
                      tooltip: 'Close'))
            ])));
  }

  Widget _buildRunningRecordPage(BuildContext context, int stepNum) {
    double paddingTop = GetPlatform.isIOS ? 0 : 20;
    return Container(
        width: double.infinity,
        color: Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
        margin: EdgeInsets.fromLTRB(20, paddingTop, 20, 20),
        padding: EdgeInsets.all(10),
        child: _buildMainWidget(context, stepNum));
  }

  Widget _buildMainWidget(BuildContext context, int stepNum) {
    // 0:起始页  1:主页
    if (stepNum > -1) {
      ExamIbRecord? item = controller.recordsGrades!;
      const Color headGreenTextColor = Color(0xff59A59A);

      const StrutStyle strutStyle = StrutStyle(
        forceStrutHeight: true,
        leading: 0.5,
      );

      return Padding(
          padding: EdgeInsets.only(left: 20, right: 20),
          child: Column(children: [
            Column(
              children: [
                Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
                  Text(item.className ?? '',
                      style: TextStyle(
                          color: headGreenTextColor,
                          fontSize: 26,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.8)),
                  Text('(${item.classId})',
                      style: TextStyle(
                          color: headGreenTextColor,
                          fontSize: 14,
                          letterSpacing: -0.5)),
                  Text(' / IB speaking for ',
                      style: TextStyle(
                          color: blackTextColor,
                          fontSize: 14,
                          letterSpacing: -0.5)),
                  Text(item.userName ?? '',
                      style: TextStyle(
                          color: headGreenTextColor,
                          fontSize: 16,
                          letterSpacing: -0.5))
                ]),
                Container(
                    margin: EdgeInsets.fromLTRB(70, 20, 70, 10),
                    padding: EdgeInsets.fromLTRB(20, 7, 20, 7),
                    color: Get.isDarkMode ? Colors.white10 : Color(0x0D000000),
                    child: Row(children: [
                      Text('Title: ',
                          strutStyle: strutStyle,
                          style: TextStyle(
                              color: blackTextColor,
                              fontSize: 16,
                              fontWeight: FontWeight.w700)),
                      Text('${item.title} | ',
                          strutStyle: strutStyle,
                          style: TextStyle(
                              color: blackTextColor,
                              fontSize: 16,
                              letterSpacing: -0.5)),
                      Text('Recorded: ',
                          strutStyle: strutStyle,
                          style: TextStyle(
                              color: blackTextColor,
                              fontSize: 16,
                              fontWeight: FontWeight.w700)),
                      Text(
                          DateFormat('MM/d/yyyy').format(
                              DateTime.fromMillisecondsSinceEpoch(
                                  item.commitTime!)),
                          strutStyle: strutStyle,
                          style: TextStyle(
                              color: blackTextColor,
                              fontSize: 16,
                              fontWeight: FontWeight.w500))
                    ]))
              ],
            ),
            SizedBox(height: 20),
            // Main
            Expanded(
                child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                  Expanded(
                      flex: 7,
                      child: Container(
                        decoration: BoxDecoration(
                            border: Border.all(
                              color: Get.isDarkMode
                                  ? AppTheme.colors.darkTheme2
                                  : Color(0xffDEE2E6),
                              width: 1,
                            ),
                            color: Get.isDarkMode
                                ? Colors.white10
                                : Color(0xFFF8F9FA),
                            boxShadow: [
                              BoxShadow(
                                  blurRadius: 4,
                                  spreadRadius: 4,
                                  offset: Offset(0, 6),
                                  color: Colors.black.withOpacity(0.1)),
                            ]),
                        child: Scrollbar(
                            child: SingleChildScrollView(
                                primary: true,
                                child: Padding(
                                    padding:
                                        EdgeInsets.only(left: 30, right: 30),
                                    child:
                                        _buildLeftWidget(context, stepNum)))),
                      )),
                  SizedBox(width: 40),
                  Expanded(
                      flex: 4,
                      child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                color: Get.isDarkMode
                                    ? AppTheme.colors.darkTheme2
                                    : Color(0xffDEE2E6),
                                width: 1,
                              ),
                              color: Get.isDarkMode
                                  ? Colors.white10
                                  : Color(0xFFF8F9FA),
                              boxShadow: [
                                BoxShadow(
                                    blurRadius: 4,
                                    spreadRadius: 4,
                                    offset: Offset(0, 6),
                                    color: Colors.black.withOpacity(0.1)),
                              ]),
                          child: _buildRightWidget(context, stepNum)))
                ])),
            SizedBox(height: 30),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: Obx(() => Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      if (controller.stepTop.value != -1)
                        ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              textStyle: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Montserrat',
                                  letterSpacing: 0.2,
                                  fontWeight: FontWeight.bold),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 42,
                                  vertical: GetPlatform.isWeb ? 20 : 12),
                              backgroundColor:
                                  (stepNum == 0 || controller.isSingleView)
                                      ? Get.isDarkMode
                                          ? Colors.white10
                                          : Color(0xFFDEDEDE)
                                      : Get.isDarkMode
                                          ? Colors.white54
                                          : Color(0xFF35A95D),
                              foregroundColor:
                                  (stepNum == 0 || controller.isSingleView)
                                      ? Colors.black45
                                      : Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              elevation: 10,
                            ),
                            onPressed: () {
                              if (stepNum == 0 || controller.isSingleView) {
                                Get.back();
                              } else {
                                controller.prevPage();
                              }
                            },
                            child: Text(
                                (stepNum == 0 || controller.isSingleView)
                                    ? 'BACK'
                                    : 'PREV')),
                      ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            textStyle: TextStyle(
                                fontSize: 20,
                                fontFamily: 'Montserrat',
                                letterSpacing: 0.2,
                                fontWeight: FontWeight.bold),
                            padding: EdgeInsets.symmetric(
                                horizontal: 42,
                                vertical: GetPlatform.isWeb ? 20 : 12),
                            backgroundColor: Get.isDarkMode
                                ? Colors.white54
                                : Color(0xFF35A95D),
                            foregroundColor: whiteTextColor,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8)),
                            elevation: 15,
                          ),
                          onPressed: () {
                            if (stepNum < 2) {
                              if (controller.isCompleted) {
                                controller.nextPage();
                              } else {
                                controller.submitPageData();
                              }
                            }
                          },
                          child: Text(stepNum == 1 ? 'SUBMIT' : 'NEXT'))
                    ],
                  )),
            )
          ]));
    }
    return Container(
        height: MediaQuery.of(context).size.height, color: Colors.transparent);
  }

  Widget _buildRightWidget(BuildContext context, int stepNum) {
    List<Widget> widgetList = [];
    widgetList.add(SizedBox(height: 50));
    List<String> scoreNames = [
      'Criterion A',
      'Criterion B1',
      'Criterion B2',
      'Criterion C'
    ];
    for (int i = 0; i < scoreNames.length; i++) {
      widgetList.add(_buildScoreItem(scoreNames[i], i, i == 0));
    }

    return SingleChildScrollView(
        child: Container(
            constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height - 320),
            padding: EdgeInsets.only(left: 30, right: 30),
            child: Column(children: widgetList)));
  }

  Widget _buildScoreItem(String scoreName, int index, bool isFirst) {
    List<Widget> options = [];
    List<String> numList = [];
    const scoreKey = ['A', 'B1', 'B2', 'C'];
    String defaultValue = '0';
    Map map = controller.selectorMap;
    if (map.containsKey(scoreKey[index])) {
      defaultValue = map[scoreKey[index]];
    }
    numList.add('reviewed');
    for (int i = 0; i <= (index == 0 ? 12 : 6); i++) {
      numList.add(i.toString());
    }

    options.add(Row(children: [
      Text(scoreName,
          style: TextStyle(
              color: blackTextColor,
              fontSize: 18,
              fontWeight: FontWeight.w700)),
      _buildAlertIconButton(index)
    ]));
    options.add(SizedBox(height: 5));
    if ((controller.isSingleView && index == 1) || controller.isCompleted) {
      options.add(Container(
          constraints: BoxConstraints(maxWidth: 300),
          padding: EdgeInsets.only(left: 10, right: 10),
          decoration: BoxDecoration(
              border: Border.all(
                color: Get.isDarkMode
                    ? AppTheme.colors.darkTheme2
                    : Colors.black54,
                width: 1,
              ),
              color: Get.isDarkMode ? Colors.white10 : Colors.white),
          child: DropdownButtonFormField<String>(
            value: defaultValue,
            onChanged: null,
            items: numList.map((String option) {
              return DropdownMenuItem(
                  value: option,
                  child: Text(option == 'reviewed' ? '暂不评分' : option));
            }).toList(),
          )));
    } else {
      options.add(Container(
          constraints: BoxConstraints(maxWidth: 300),
          padding: EdgeInsets.only(left: 10, right: 10),
          decoration: BoxDecoration(
              border: Border.all(
                color: Get.isDarkMode
                    ? AppTheme.colors.darkTheme2
                    : Colors.black54,
                width: 1,
              ),
              color: Get.isDarkMode ? Colors.white10 : Colors.white),
          child: DropdownButtonFormField<String>(
            value: defaultValue,
            onChanged: (String? newPosition) {
              controller.selectorMap[scoreKey[index]] = newPosition;
            },
            items: numList.map((String option) {
              return DropdownMenuItem(
                  value: option,
                  child: Text(option == 'reviewed' ? '暂不评分' : option));
            }).toList(),
          )));
    }

    options.add(SizedBox(height: 20));
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start, children: options);
  }

  Widget _buildLeftWidget(BuildContext context, int stepNum) {
    if (stepNum == 0) {
      QuestionContent element = controller
          .assessmentResult!.list![0].questions![0].question![0].head!;
      List? answer = controller
          .assessmentResult!.list![0].questions![0].question![0].answer;
      String audioId = '';
      if (answer != null && answer.isNotEmpty) {
        audioId = answer[0];
      }
      return Container(
          constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height - 320),
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            Visibility(
                visible: element.image != null && element.image != '',
                child: SizedBox(
                    width: double.infinity > 500 ? 500 : double.infinity,
                    child: Image.network(element.image ?? ''))),
            RichText(
                text: TextSpan(
                    text: element.text ?? '',
                    style: TextStyle(
                      fontFamily: 'Noto Sans SC',
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color:
                          (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
                    ),
                    children: [
                  WidgetSpan(
                      child: Visibility(
                          visible: element.audio != null,
                          child: Container(
                              padding: EdgeInsets.fromLTRB(6, 4, 6, 0),
                              height: 40,
                              width: 52,
                              child: IconButton(
                                iconSize: 40,
                                padding: EdgeInsets.zero,
                                icon: Icon(
                                  Icons.volume_up,
                                  color: Colors.orange,
                                ),
                                onPressed: () {
                                  BGSinglePlayer().play(element.audio);
                                },
                              ))))
                ])),
            SizedBox(height: 20),
            audioId.isEmpty
                ? Container(
                    decoration: BoxDecoration(
                        border: Border.all(
                          color: Get.isDarkMode
                              ? AppTheme.colors.darkTheme2
                              : Color(0xffbee5eb),
                          width: 1,
                        ),
                        borderRadius: BorderRadius.circular(6),
                        color: Get.isDarkMode
                            ? Colors.white10
                            : Color(0xffd1ecf1)),
                    width: MediaQuery.of(context).size.width * 0.4,
                    padding: EdgeInsets.all(10),
                    child: Text(
                        "He/She didn't record anything for this question.",
                        style: TextStyle(
                            fontSize: 18,
                            color: Get.isDarkMode
                                ? blackTextColor
                                : Color(0xff0c5460),
                            height: 1.4)),
                  )
                : SampleAudioPlayer(
                    name: 'audioPlayerEvaluation',
                    audioId: audioId,
                    audioUrl: '',
                  )
          ]));
    } else if (stepNum == 1) {
      List<Widget> options = [];
      var questions;
      if (controller.isSingleView) {
        questions =
            controller.assessmentResult!.list![0].questions![0].question!;
      } else {
        questions =
            controller.assessmentResult!.list![0].questions![1].question!;
      }

      options.add(SizedBox(height: 20));
      for (QuestionItem question in questions) {
        options.add(_buildSpeakItem(context, question));
      }
      options.add(SizedBox(height: 20));
      return Column(children: options);
    }
    return SizedBox();
  }

  Widget _buildSpeakItem(BuildContext context, QuestionItem item) {
    List<Widget> options = [];
    options.add(ExamUtil.buildHeadInfoWidget(item.head, context));
    options.add(SizedBox(height: 25));
    if (item.answer != null &&
        item.answer!.length > 0 &&
        item.answer![0].isNotEmpty) {
      options.add(SampleAudioPlayer(
        name: 'audioPlayerEvaluation',
        audioId: item.answer![0],
        audioUrl: '',
      ));
    } else {
      options.add(Container(
        decoration: BoxDecoration(
            border: Border.all(
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2
                  : Color(0xffbee5eb),
              width: 1,
            ),
            borderRadius: BorderRadius.circular(6),
            color: Get.isDarkMode ? Colors.white10 : Color(0xffd1ecf1)),
        width: MediaQuery.of(context).size.width * 0.4,
        padding: EdgeInsets.all(10),
        child: Text("He/She didn't record anything for this question.",
            style: TextStyle(
                fontSize: 18,
                color: Get.isDarkMode ? blackTextColor : Color(0xff0c5460),
                height: 1.4)),
      ));
    }
    options.add(SizedBox(height: 35));
    options.add(Flex(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      direction: Axis.horizontal,
      children: List.generate(
          (MediaQuery.of(Get.context!).size.width * 0.1).toInt(), (_) {
        return SizedBox(
          width: 4,
          height: 2,
          child:
              DecoratedBox(decoration: BoxDecoration(color: Color(0xFFCCCCCC))),
        );
      }),
    ));

    options.add(SizedBox(height: 20));

    return Column(
        crossAxisAlignment: CrossAxisAlignment.start, children: options);
  }
}

Widget _buildAlertIconButton(int index) {
  return Container(
    width: 32,
    height: 32,
    margin: EdgeInsets.only(left: 5),
    decoration: BoxDecoration(
        border: Border.all(
          color: Color(0xffDEE2E6),
          width: 1,
        ),
        borderRadius: BorderRadius.circular(16),
        color: Get.isDarkMode ? Colors.white54 : Color(0xFFFFB10D)),
    child: IconButton(
        iconSize: 24,
        padding: EdgeInsets.zero,
        onPressed: () {
          showGeneralDialog(
              context: Get.context!,
              transitionDuration: const Duration(milliseconds: 400),
              pageBuilder: (bc, ania, anis) {
                return _alertFluencyScoreInfoPage(index);
              });
        },
        icon: Icon(Icons.question_mark,
            color: Get.isDarkMode ? Colors.black54 : Colors.white)),
  );
}

Widget _alertFluencyScoreInfoPage(int index) {
  String showStr = '<div></div>';
  double height = 0;
  switch (index) {
    case 0:
      height = MediaQuery.of(Get.context!).size.height * 0.65;
      showStr =
          '<div><h3>&nbsp;</h3><h4 style="text-align: center;">10-12 通常准确且非常有效地掌握了所学语言</h4><p>使用的词汇适合作业，表达方式细致且多种多样，加强了讯息的传达，而且目的明确地使用了习惯用语。有选择地使用了多种多样的基本的和较复杂的语法结构，以便加强沟通交流。语言大都准确。在较复杂的语法结构中有小错误，不妨碍交流。 语音和语调非常清楚，并加强了沟通交流。</p></div><div><h4 style="text-align: center;">7-9 有效并通常准确地掌握了所学语言</h4><p>使用的词汇适合作业，并且多种多样，包括了对习惯用语的使用。 有效地使用了各种各样基本的和较为复杂的语法结构。 语言大都准确。在基本的和复杂的语法结构中偶尔有错，不妨碍交流。 语音和语调通常清楚，不妨碍交流。</p></div><div><h4 style="text-align: center;">4-6 部分有效地掌握了所学语言</h4><p>使用的词汇通常适合作业，并且多种多样。 多样化地使用了基本的和一些较复杂的语法结构。在基本结构方面语言总体上准确，但在一些比较复杂的结构中有错误。错误 偶尔妨碍交流。语音和语调通常清楚。</p></div><div><h4 style="text-align: center;">1-3 对所学语言掌握得有限</h4><p>使用的词汇有时适合作业。 使用了一些基本的语法结构，有一些使用更复杂结构的尝试。 语言在基本结构和较复杂的结构中都含有错误。错误妨碍交流。 语音和语调通常清楚，但有时会妨碍交流。</p></div><div><h4 style="text-align: center;">0</h4><p>作业没有达到以上细则描述的任何标准。</p></div></div><h3>&nbsp;</h3></div>';
      break;
    case 1:
      height = MediaQuery.of(Get.context!).size.height * 0.53;
      showStr =
          '<div><h3>&nbsp;</h3><h4 style="text-align: center;">5-6 口头表达始终与文学作品节选相关而且令人信服</h4><p>考生有效地使用了节选。参考节选有效地展开和支持评论和见解。</p></div><div><h4 style="text-align: center;">3-4 口头表达与文学作品节选通常相关</h4><p>考生胜任地使用了文学作品节选。参考节选来展开和支持一些评论和见解。</p></div><div><h4 style="text-align: center;">1-2 口头表达通常与启发材料无关联</h4><p>考生肤浅地使用了节选。评论与见解笼统空泛、过分简单而且大都没有得到支持。</p></div><div><h4 style="text-align: center;">0</h4><p>作业没有达到以上细则描述的任何标准。</p></div></div><h3>&nbsp;</h3></div>';
      break;
    case 2:
      height = MediaQuery.of(Get.context!).size.height * 0.53;
      showStr =
          '<div><h3>&nbsp;</h3><h4 style="text-align: center;">5-6 考生的回答始终与问题相关，并显示了一些展开</h4><p>回答始终恰当而且得到了展开。 回答有深度和广度，包含个人的解读和/或与对话者交流的尝试。</p></div><div><h4 style="text-align: center;">3-4 考生的回答通常与问题相关</h4><p>大部分回答恰当，有些得到了展开。 大多数回答有深度和广度。</p></div><div><h4 style="text-align: center;">1-2 考生一直在努力回答问题</h4><p>有些回答是恰当的，但很少展开。 回答的深度和范围都有限。</p></div><div><h4 style="text-align: center;">0</h4><p>作业没有达到以上细则描述的任何标准。</p></div></div><h3>&nbsp;</h3></div>';
      break;
    case 3:
      height = MediaQuery.of(Get.context!).size.height * 0.53;
      showStr =
          '<div><h3>&nbsp;</h3><h4 style="text-align: center;">5-6 一贯保持着理解和互动交流</h4><p>考生能用所学语言回答而且表现出理解。 切实地参与了会话，并提出了一些独到的见解。</p></div><div><h4 style="text-align: center;">3-4 通常都能够理解并进行互动交流</h4><p>考生能够用所学语言回答而且通常表现出理解。 通常能够保持参与。</p></div><div><h4 style="text-align: center;">1-2 理解和互动交流有限</h4><p>考生用所学语言做了有限的回答。 有限地参与了对话。大多数问题必须被重述和/或改述才能够理解。</p></div><div><h4 style="text-align: center;">0</h4><p>作业没有达到以上细则描述的任何标准。</p></div></div><h3>&nbsp;</h3></div>';
      break;
  }
  return AlertDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      content: Container(
          width: MediaQuery.of(Get.context!).size.width * 0.6,
          height: height,
          child: Column(children: [
            SizedBox(
                height: height - 54,
                child: SingleChildScrollView(
                    child: HtmlWidget(
                  showStr,
                  textStyle: TextStyle(
                      color: Get.isDarkMode ? Colors.white54 : Colors.black,
                      height: 1.4),
                ))),
            const SizedBox(height: 5),
            ElevatedButton(
                style: ElevatedButton.styleFrom(
                    textStyle: TextStyle(
                        fontSize: 18,
                        fontFamily: 'Montserrat',
                        fontWeight: FontWeight.bold),
                    padding: EdgeInsets.symmetric(
                        horizontal: 32, vertical: GetPlatform.isWeb ? 20 : 12),
                    backgroundColor:
                        Get.isDarkMode ? Colors.white54 : Color(0xFF35A95D),
                    foregroundColor:
                        Get.isDarkMode ? Colors.black54 : Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    )),
                onPressed: () {
                  Get.back();
                },
                child: Text('OK'))
          ])));
}
